<?php

namespace App\Api;

use PhalApi\Api;
use PhalApi\Cache;

/**
 * 万华普曼
 *   @desc 禁毒平台
 */
class Whpm extends Api
{

    public function getRules()
    {
        return array(
            'getSMS' => array(
                "phone" => array('name' => 'phone', 'type' => 'string', 'require' => true, 'desc' => 'phone'),
            ),
            'login' => array(
                "enduser" => array('name' => 'enduser', 'type' => 'string', 'require' => true, 'desc' => 'enduser'),
                "cypher" => array('name' => 'cypher', 'type' => 'string', 'require' => true, 'desc' => 'cypher'),
                "smCode" => array('name' => 'smCode', 'type' => 'string', 'require' => true, 'desc' => 'smCode'),
            ),
            'login_web' => array(
                "enduser" => array('name' => 'enduser', 'type' => 'string', 'require' => true, 'desc' => 'enduser'),
                "cypher" => array('name' => 'cypher', 'type' => 'string', 'require' => true, 'desc' => 'cypher'),
                "smCode" => array('name' => 'smCode', 'type' => 'string', 'require' => true, 'desc' => 'smCode'),
                "userNum" => array('name' => 'userNum', 'type' => 'string', 'require' => true, 'desc' => 'userNum'),
                "deviceIMEI" => array('name' => 'deviceIMEI', 'type' => 'string', 'require' => true, 'desc' => 'deviceIMEI'),
                "deviceMAC" => array('name' => 'deviceMAC', 'type' => 'string', 'require' => true, 'desc' => 'deviceMAC'),
            ),
            'uploadCR' => array(),
        );
    }

    
    //加密
    function aes_encrypt($content) {
        $key = "dplyjc";
        $key= substr(openssl_digest(openssl_digest($key, 'sha1', true), 'sha1', true), 0, 16);
        $cipher_algo="AES-128-CBC";
        $encryptContent = openssl_encrypt(
        $content,
        $cipher_algo,
        $key,
        OPENSSL_RAW_DATA,
        '');
        $encryptContent = base64_encode($encryptContent);
        return $encryptContent;
    }



    /**
     * 获取短信
     */

    public function getSMS(){
        //这里是钉钉提示的开始
        $curl = new \PhalApi\CUrl();
        // 设置请求的头部信息。
        $curl->setHeader(array('Content-Type' => 'multipart/form-data'));
        // 设置curl选项
        $postData = array(
            "operatorCode" => $this->phone,
        );
        $postData["encryptJson"] = $this->aes_encrypt($this->phone);
        // return $postData;

        $url = "https://dplyjg.gat.zj.gov.cn:10000/api/web/utilities/custom/getSMS";
        $res = $curl->post($url, $postData, 2000);
        return json_decode($res);
    }


    /**
     * 登录完成
     */

     public function login_web(){
        //这里是钉钉提示的开始
        $curl = new \PhalApi\CUrl();
        // 设置请求的头部信息。
        $curl->setHeader(array('Content-Type' => 'multipart/form-data'));
        // 设置curl选项
        $postData = array(
            "enduser" => $this->enduser,
            "cypher" => $this->cypher,
            "userNum" => $this->userNum,
            "deviceIMEI" => $this->deviceIMEI,
            "deviceMAC" => $this->deviceMAC,
            "devicelat" => "69.16001",
            "devicelng" => "120.121212",
            "loginTime" => date("YmdHis", time()),
            "loginLocation" => "丽水市莲都区禁毒办",
            "smCode" => $this->smCode,
        );
        $postData["encryptJson"] = $this->aes_encrypt(json_encode($postData));
        $data = array(
            "encryptJson" => $postData["encryptJson"]
        );

        $url = "https://dplyjg.gat.zj.gov.cn:10000/api/web/utilities/custom/login";
        $res = $curl->post($url, $data, 2000);
        $resData = json_decode($res, true);

        // $res = '{ "sys": "success", "code": 1, "data": { "uid": "1688820938763800576", "token": "eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMTY4ODgyMDkzODc2MzgwMDU3NiIsInVzZXJfbmFtZSI6IjE1MjE1NzM3MjUwIiwic2NvcGUiOlsiYWxsIl0sImV4cCI6MjAyODQ1NDk3OSwiaXNNYW4iOmZhbHNlLCJhdXRob3JpdGllcyI6WyLnpoHmr5Llip4iXSwiY2xpZW50X2lkIjoidGVzdDEifQ.OSJsYFDX3U7uV9WLdFkvBadawQfitwgK81R98c5m-Sc" }, "messages": "operator login success!" }';
        // $resData = json_decode($res, true);

        if ( $resData['sys'] == "success"){
            $has = \PhalApi\DI()->notorm->idcard_zlb_username->where( array( 'enduser' => $this->enduser ) )->fetchOne();
            if($has){
                \PhalApi\DI()->notorm->idcard_zlb_username->where( array( 'enduser' => $this->enduser ) )->update( array(
                    'cypher' => $this->cypher,
                    'uid' => $resData['data']['uid'],
                    'token' => $resData['data']['token'],
                ));
            }else{
                \PhalApi\DI()->notorm->idcard_zlb_username->insert( array( 
                    'enduser' => $this->enduser, 
                    'cypher' => $this->cypher, 
                    'uid' => $resData['data']['uid'], 
                    'token' => $resData['data']['token']
                    ) 
                );
            }
        }
        return $resData;
    }

    /**
     * 登录完成
     */

     public function login(){
        //这里是钉钉提示的开始
        $curl = new \PhalApi\CUrl();
        // 设置请求的头部信息。
        $curl->setHeader(array('Content-Type' => 'multipart/form-data'));
        // 设置curl选项
        $postData = array(
            "enduser" => $this->enduser,
            "cypher" => $this->cypher,
            "userNum" => "pb-01m220200102",
            "deviceIMEI" => "460030912121001",
            "deviceMAC" => "00-01-6C-06-A6-29",
            "devicelat" => "69.16001",
            "devicelng" => "120.121212",
            "loginTime" => date("YmdHis", time()),
            "loginLocation" => "丽水市莲都区禁毒办",
            "smCode" => $this->smCode,
        );
        $postData["encryptJson"] = $this->aes_encrypt(json_encode($postData));
        $data = array(
            "encryptJson" => $postData["encryptJson"]
        );

        $url = "https://dplyjg.gat.zj.gov.cn:10000/api/web/utilities/custom/login";
        $res = $curl->post($url, $data, 2000);
        return json_decode($res) ? json_decode($res) : $res;
    }


    /**
     * 上传记录
     */

     public function PushData($data){

        $MachineCode = $data['EQMAC'];
        $token_info = \PhalApi\DI()->notorm->idcard_zlb_username->where( array( 'MachineCode' => $MachineCode ) )->fetchOne();
        $data['CheckAccount'] = $token_info['uid'];
        $data['CheckAddress'] = $token_info['CheckAddress'];
        $data['CheckName'] = $token_info['CheckName'];

        $curl = new \PhalApi\CUrl();
        // 设置请求的头部信息。
        $header = array(
            'Content-Type' => 'multipart/form-data',
        );
        $header['authorization'] = $token_info['token'];
        $curl->setHeader($header);

        $postData = array(
            'encryptJson' => $this->aes_encrypt(json_encode($data)),
        );

        \PhalApi\DI()->logger->debug('PushData', $data);
        \PhalApi\DI()->logger->debug('header', $header);

        $url = "https://dplyjg.gat.zj.gov.cn:10000/api/web/utilities/custom/drugdetectRecord/uploadCR";
        $res = $curl->post($url, $postData, 60000);
        $arr = json_decode($res) ? json_decode($res) : $res;

        $curl->setHeader(array('Content-Type' => 'application/json'));
        $url = 'https://oapi.dingtalk.com/robot/send?access_token=c230bf201cf694db851c14413af45f3c216754466886f7f46647eb3678d809a4';
        $url2 = 'https://oapi.dingtalk.com/robot/send?access_token=09d6f6a9ba294b1e5bf1452d73e47a00b213f8dc7b6991df7c8720b79ec8046c';
        $dingdingdata = array(
            'msgtype' => 'text',
            'text' => array(
                "content" => "通知：" . $res
            )
        );
        $curl->post($url, json_encode($dingdingdata), 2000);
        $curl->post($url2, json_encode($dingdingdata), 2000);
        return json_decode($res, true);
    }



    /**
     * 上传记录
     */

     public function uploadCR(){
        // $json_data = file_get_contents('php://input');
        // 解码 JSON 数据
        // $data = json_decode($json_data, true);
        $allow = array(
            "3837609A"
        );

        $record = \PhalApi\DI()->notorm->idcard_ms_result
        ->where( array(
            'MachineCode' => $allow,
            'push' => 'no'
        ) )
        ->fetchAll();


        $needName = array(
            "甲基安非他命(ME" => "冰毒",
            "冰毒(MET)" => "冰毒",
            "吗啡(MOP)" => "吗啡",
        );

        if ( $record ){

            $newData = [];
            foreach ($record as $item) {
                $key = $item['SerialNumber'];
                if (!isset($newData[$key])) {
                    $newData[$key] = [];
                }
                $newData[$key][] = $item;
            }

            $SerialNumberlist =[];
            $print = [];
            $all = [];

            // return $newData;
            foreach ($newData as $key => $value) {
                $need_data = [];
                $need_data['SerialNumber'] = $key;
                $SerialNumberlist[$key] = [];

                if ( count($value) > 0 ){
                    foreach ($value as $item) {
                        $one = array(
                            "PillIdentified" => "否",
                            "CValue" => "0.12 ",
                            "CPosition" => "4687.1531 ",
                            "TValue" =>"0.22",
                            "TPosition" =>     "2347.1221 ",
                            "TvCValue"=>"466.566",
                            "Concentration"=> "8",
                            "ReferenceValue"=> "0.2",
                            "ConcentrationUnit"=> "ng/mg",
                            "TestResult"=> "阴性",
                            "DrugsName"=> "吗啡",
                            "TestTime"=> time() .'00'
                        );
                        $one['DrugsName'] = $needName[$item['SubProjectName']] ? $needName[$item['SubProjectName']]:$item['SubProjectName'];
                        $numbersAndDot = preg_replace('/[^\d.<]/', '', $item['Result']);
                        $one['CValue'] = $numbersAndDot == '<0.2' ? '0.00' : $numbersAndDot;
                        $one['Concentration'] = $one['CValue'];
                        if ( $numbersAndDot != '<0.2' ){
                            if( $numbersAndDot >= 0.2){
                                $one['TestResult'] = '阳性';
                                $one['PillIdentified'] = '是';
                            }
                        }
                        $need_data['EQMAC'] = $item['MachineCode'];
                        $need_data['SampleNo'] = $item['SampleNo'];
                        $need_data['TestResult'][] = $one;
                        $need_data['spectrum'] = $item['spectrum'];
                        $need_data['PillName'][] = $needName[$item['SubProjectName']] ? $needName[$item['SubProjectName']]:$item['SubProjectName'];
                    }
                }

                $need_data['PillName'] = implode(',', $need_data['PillName']);
                $all[] = $need_data;

    
                // 设置curl选项
                $postData = array(
                    "ReagentCard" => "91-ZheJ-DuPLYJG-JinD-YingG-MaoF-BingD-WanHPM-990f53-20240318-01-1234567",
                    "CheckPill" => "1",
                    "PillName" => "吗啡",
                    "deviceCode" => "662023120015",
                    "CheckAddress" => "丽水市莲都区禁毒办",
                    "Lat" => "69.16001",
                    "Lng" => "120.121212",
                    "EnclosurePath" => "",
                    "SampleNo" => "%edd(fei(?;;?g!!d",
                    "CheckAccount" => "1768127317571407872",
                    "spectrum" => "[1137,271,373,353,275,1002,552,955,718,1166,1880,1137,271,373,353,275,1002,552,955,1718,1166,8801,137,271,373,353,275,1002,552,955,718,1166,880,1137,271,373,353,275,1002,552,955,718,1166,880,1137,271,373,353,275,1002,552,955,718,1166,8801,137,271,373,353,275,1002,552,955,718,1166,880,1137,271,373,353,275,1002,552,955,718,1166,880,1137,271,373,353,275,1002,552,955,718,1166,8801,137,271,373,353,275,1002,552,955,718,1166,880,1137,271,373,353,275,1002,552,955,718,1166,880,1137,271,373,353,275,1002,552,955,718,1166,8801,137,271,373,353,275,1002,552,955,718,1166,880,1137,271,373,353,275,1002,552,955,718,1166,880,1137,271,373,353,275,1002,552,955,718,1166,8801,137,271,373,353,275,1002,552,955,718,1166,8801137,271,373,353,275,1002,552,955,718,1166,880,1137,271,373,353,275,1002,552,955,718,1166,8801,137,271,373,353,275,1002,552,955,718,1166,8801137,271,373,353,275,1002,552,955,718,1166,880,1137,271,373,353,275,1002,552,955,718,1166,8801,137,271,373,353,275,1002,552,955,718,1166,8801137,271,373,353,275,1002,552,955,718,1166,880,1137,271,373,353,275,1002,552,955,718,1166,8801,137,271,373,353,275,1002,552,955,718,1166,880,1137,271,373,353,275,1002,552,955,718,1166,880,1137,271,373,353,275,1002,552,955,718,1166,8801,137,271,373,353,275,1002,552,955,718,1166,8801137,271,373,353,275,1002,552,955,718,1166,880,1137,271,373,353,275,1002,552,955,718,1166,8801,137,271,373,353,275,1002,552,955,718,1166,880]",
                    "BatchNo" => "20200101001",
                    "CheckName" => "丽水市莲都区禁毒办",
                    "CheckPhone" => "15215737250",
                    "CheckCompany" => "禁毒社区",
                    "Supervisor" => "丽水市莲都区禁毒办",
                    "typeID" => "2",
                    "UnpackTime" => date("Y-m-d H:i:s", time()),
                    "ChoiceTime" => date("Y-m-d H:i:s", time()),
                    "CheckTech" => "荧光检测",
                    "EQType" => "毒品痕量检测仪",
                    "EQBrand" => "WH-FAR-300",
                    "EQMAC" => "460030912121001",
                    "EQCertifiedBody" => "司法认证中心",
                    "CertifiedItem" => "毛发",
                    "Is_Certified" => "1",
                    "CertifiedTime" => "2023/3/9",
                    "CertifiedID" => "公京检第1932070号",
                    "PicRemarks" => "备注样例",
                    "VoicesRemarks" => "备注样例",
                    "TestResult" => array(
                        array(
                            "PillIdentified" =>"否",
                            "CValue" =>"0.12 ",
                            "CPosition" =>"4687.1531 ",
                            "TValue" =>"0.22",
                            "TPosition" =>"2347.1221 ",
                            "TvCValue" =>"466.566",
                            "Concentration" =>"8",
                            "ReferenceValue" =>"0.2",
                            "ConcentrationUnit" =>"ng/mg",
                            "TestResult" =>"阳性",
                            "DrugsName" =>"吗啡",
                            "TestTime" =>1593840251570
                        )
                    ),
                );

                //工号 10085787 这个客服，提供了那么多证据，也无动于衷（让人心寒）
                //工号 10047444

                $postData['SampleNo'] = $need_data['SampleNo'];
                $postData['EQMAC'] = $need_data['EQMAC'];
                // 获取当前的月份、小时和分钟
                $month = date('m'); // 两位数表示的当前月份
                $hour = date('H'); // 两位数表示的当前小时
                $minute = date('i'); // 两位数表示的当前分钟
                // 生成最后两位随机数
                $random = mt_rand(0, 9);
                // 组合成7位数
                $DigitNumber = $month . $hour . $minute . $random;
                $postData['ReagentCard'] = "91-ZheJ-DuPLYJG-JinD-YingG-MaoF-BingD-WanHPM-990f53-".date("Ymd")."-01-".$DigitNumber;
                $postData['BatchNo'] = $DigitNumber;
                $postData['PillName'] = $need_data['PillName'];
                $postData['spectrum'] = $need_data['spectrum'];
                $postData['TestResult'] = $need_data['TestResult'];
                $SerialNumberlist[$key] = $postData['PillName'];
                $print[] = $postData;

                //把已经发送更新为已经发送
                // return $postData;

                $res = $this->PushData($postData);
                if( $res['sys'] == 'success' ){
                    \PhalApi\DI()->notorm->idcard_ms_result
                    ->where( array(
                        'SerialNumber' => $key,
                    ) )
                    ->update( array(
                        'push' => $res['messages']
                    ));
                    return array($res, $postData);
                }else{
                    \PhalApi\DI()->notorm->idcard_ms_result
                    ->where( array(
                        'SerialNumber' => $key,
                    ) )
                    ->update( array(
                        'push' =>$res['messages']
                    ));
                    return array($res, $postData);
                }
            }

            // return  $SerialNumberlist;
            return  $print;
        }
    }

}
